package com.wholesmart.common.security.listener;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.wholesmart.common.security.properties.BrowserSecurityProperties;
import com.wholesmart.service.UserService;

/**
 * 记录登陆次数等信息
 * 
 * @author dyw
 * @date 2019年11月26日
 */
@Component
public class LoginAttemptService {
	private LoadingCache<String, Integer> attemptsCache;
	@Autowired
	private UserService userService;
	@Autowired
	private BrowserSecurityProperties browserSecurityProperties;

	public LoginAttemptService() {
		super();
		attemptsCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.DAYS)
				.build(new CacheLoader<String, Integer>() {
					public Integer load(String username) {
						return 0;
					}
				});
	}

	public void loginSucceeded(String username) {
		attemptsCache.invalidate(username);
	}

	public void loginFailed(String username) {
		int attempts = 0;
		try {
			attempts = attemptsCache.get(username);// 从缓存中获取已登录次数
		} catch (ExecutionException e) {
			attempts = 0;// 没有获取到就是0
		}
		attempts++;
		if (attempts > (browserSecurityProperties.getMaxAttempt() - 1)) {// 如果登陆次数超过指定次数，锁定用户，清空登陆缓存次数
			userService.setUserStatusByUsername(username, 1);
			attemptsCache.invalidate(username);
		} else {
			attemptsCache.put(username, attempts);
		}
	}

	public boolean isBlocked(String key) {
		try {
			return attemptsCache.get(key) >= (browserSecurityProperties.getMaxAttempt() - 1);
		} catch (ExecutionException e) {
			return false;
		}
	}
}
